//----------------------------------------------------------- // Purpose: Demonstrate how strings can be broken into tokens. // Author: John Gauch //----------------------------------------------------------- #include #include using namespace std; //----------------------------------------------------------- // Function that extracts space separated tokens from input. // Returns true when token is found, and false when not found. //----------------------------------------------------------- bool get_token(string & input, string & token) { // Find start of token unsigned int start = 0; while ((start < input.length()) && (input.at(start) == ' ')) start++; // Find end of token unsigned int end = start; while ((end < input.length()) && (input.at(end) != ' ')) end++; // Extract token from input token = input.substr(start, end - start); input = input.substr(end, input.length() - end); return (token.length() > 0); } //----------------------------------------------------------- // Main program for testing. //----------------------------------------------------------- int main() { string input = " num = 42 17 + "; string token = ""; cout << "input = '" << input << "'\n"; while (get_token(input, token)) cout << "token = '" << token << "'\n"; }